package com.sms.model;

import com.sms.exception.DataFileCorruptedException;
import com.sms.util.FileUtil;
import com.sms.util.ValidateUtil;

import java.io.IOException;
import java.util.List;

import static com.sms.constants.SystemConstants.COURSE_FILE;

/**
 * 课程实体类
 * 位置：com.sms.model.Course
 */
public class Course {
    // 属性定义
    private String courseId;   // 课程ID，格式[A-Z]\\d{3}
    private String courseName; // 课程名称
    private double credit;     // 学分，0.5-10.0

    public String getCourseId() {
        return courseId;
    }

    public void setCourseId(String courseId) {
        this.courseId = courseId;
    }

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public double getCredit() {
        return credit;
    }

    public void setCredit(double credit) {
        this.credit = credit;
    }


    /**
     * 验证课程数据有效性
     *
     * @return true-数据有效, false-数据无效
     */
    public boolean isValid() {
        return ValidateUtil.isValidCourseId(this.courseId) &&
                ValidateUtil.isValidCredit(this.credit);
    }

    /**
     * 转换为文件存储格式
     *
     * @return CSV格式字符串："courseId,courseName,credit"
     */
    public String toFileString() {
        return this.courseId + "," + this.courseName + "," + this.credit +
                System.lineSeparator();
    }

    /**
     * 从文件行解析课程对象
     * @param line 文件行内容（CSV格式）
     * @return 解析后的Course对象
     * @throws IOException                当文件读取失败时抛出
     * @throws DataFileCorruptedException 当数据格式错误时抛出
     */
    public static Course fromFileString(String line) throws DataFileCorruptedException, IOException {
        List<Course> courses = FileUtil.loadCourses(COURSE_FILE);
        return courses.get(Integer.parseInt(line));
    }
}